package org.example.domain.strategy.service.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.armory.IStrategyDispatch;
import org.example.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.example.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.example.types.common.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {
    @Resource
    private IStrategyRepository repository;

//    private Long userScore=0L;

    @Resource
    protected IStrategyDispatch strategyDispatch;//抽奖

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }
    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId:{} strategyId:{} ruleModel:{}",userId,strategyId,ruleModel());

        //4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
        String ruleValue =repository.queryStrategyRuleValue(strategyId,ruleModel());


        //获取处理后范围
        Map<Long, String> analyticalValueGrop = getAnalyticalValue(ruleValue);
        if(null==analyticalValueGrop|| analyticalValueGrop.isEmpty()){
            log.info("抽奖责任链-权重告警 【策略配置权重，但是ruleValue未配置相应的值】userId:{} strategyId:{} ruleModel:{}",userId,strategyId,ruleModel());
            return  next().logic(userId,strategyId);
        }
        //转化值，排序
        List<Long> analyticalSortedKeys=new ArrayList<>(analyticalValueGrop.keySet());  //复制key4000 ,600,5000
//        Collections.sort(analyticalSortedKeys); //4,5,6000
        // 倒序排序
        Collections.sort(analyticalSortedKeys, Comparator.reverseOrder());


        Integer userScore= repository.queryActivityAccountTotalUseCount(userId,strategyId);

        //找出最小的符合值  也就是4500找4000,5001找5000
        Long nextValue=analyticalSortedKeys.stream()
                .filter(key->userScore>=key)
                .findFirst()
                .orElse(null);

        if(null!=nextValue){
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValueGrop.get(nextValue));
            log.info("抽奖责任链-权重接管 userId:{} strategyId:{} ruleModel:{}  awardId:{}",userId,strategyId,ruleModel(),awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }
        log.info("抽奖责任链-权重放行 userId:{} strategyId:{} ruleModel:{} ",userId,strategyId,ruleModel());
        //不在权重范围内--积分不够找不到--走兜底
        return  next().logic(userId,strategyId);
    }




    private Map<Long,String> getAnalyticalValue(String ruleValue){
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> reluValueMap=new HashMap<>();
        //对每个组进行处理 eg:4000:102,103,104,105
        for(String reluValueKey :ruleValueGroups){
            //检查空
            if(reluValueKey==null||reluValueKey.isEmpty()){
                return reluValueMap;
            }
            String[] splits = reluValueKey.split(Constants.COLON);//去":"，获取key和reluValue
            if(splits.length!=2){
                return  reluValueMap;//缺了
            }
            reluValueMap.put(Long.parseLong(splits[0]),reluValueKey);

        }
        return reluValueMap;
    }
}
